<?php
/**
 * Created by PhpStorm.
 * User: win10
 * Date: 2017/12/11
 * Time: 15:36
 */

namespace common\services;

use Yii;
use common\models\BaseModels;
use common\models\AccountWechat;
use common\models\kaoguobao\GoodsList;
use common\models\kaoguobao\GoodsPack;
use common\models\kaoguobao\GoodsRadio;
use common\models\kaoguobao\GoodsParams;
use common\models\kaoguobao\GoodsAmount;
use common\models\kaoguobao\User;
use common\models\kaoguobao\Order;
use common\models\kaoguobao\BenefitImg;
use common\models\kaoguobao\BenefitUser;
use common\services\tool\GnhString;

class OrderService {

    /**
     * 取消订单
     * @param $orderId
     * @return static
     */
    public static function orderCancel($orderId)
    {
        $model = Order::find()->where(['id' => $orderId])->limit(1)->one();
        // 订单不存在或者订单已支付，直接返回
        if(empty($model)){
            return '1';                                            // -订单不存在
        }elseif(!empty($model) && $model->order_status != Order::ORDER_STATUS_STAY_PAY){
            return '2';                                            // -订单已付款或已取消
        }else{
            $model->order_status = Order::ORDER_STATUS_OVERTIME;
            if($model->save()){
                return '3';                                        // -订单取消成功
            }
        }
        return false;
    }

    /**
     * 根据订单，关联查询出相关的微信信息
     * @param $orderId
     * @return array|null|\yii\db\ActiveRecord
     */
    public static function orderWechat($orderId)
    {
        return Order::find()
            ->from(Order::tableName().' as a ')
            ->leftJoin(AccountWechat::tableName().' as b ','a.wechat_id = b.ff_id')
            ->where(['a.id' => $orderId])
            ->select('a.id as order_id, a.order_num, a.user_id, a.wechat_id, a.amount, a.key, b.open_id')
            ->limit(1)
            ->asArray()
            ->one();
    }

    /**
     * 根据用户查询当前是否有未付款的订单
     * @param $wechatId
     * @param $orderType
     * @return array|bool|null|\yii\db\ActiveRecord
     */
    public static function userIsOpenOrder($wechatId, $orderType, $key)
    {
        if(empty($wechatId) || empty($orderType)){
            return false;
        }
        return Order::find()
            ->where(['wechat_id' => $wechatId])
            ->andWhere(['type' => $orderType])
            ->andWhere(['order_status' => Order::ORDER_STATUS_STAY_PAY])
            ->andWhere(['key' => $key])
            ->limit(1)
            ->one();
    }

    /**
     * 用户数据入库、受益人入库、订单生成
     * @param array $data
     * @return array|bool|static
     */
    public static function userDataCreation($data = [])
    {
        if(empty($data)){
            return false;
        }
        $amount = 100; // -产品金额（分）
        $amountModel = GoodsAmount::find()->where(['key' => $data['orderKey']])->limit(1)->one();
        if(!empty($amountModel)){
            $amount = $amountModel->amount;
        }
        // -开启事务
        $transaction = Yii::$app->db_kgb->beginTransaction();
        try {
            $userModel = User::find()->where(['wechat_id' => $data['wechatId']])->limit(1)->one();
            // 如果用户信息存在就不做新增
            if(!$userModel){
                $userModel = new User();
                $userModel->wechat_id   = $data['wechatId'];
            }
            // 先添加购买人的信息
            $userModel->user_name   = $data['userName'];
            $userModel->phone       = $data['phone'];
            if(!empty($data['birthday'])){
                $userModel->birthday    = strtotime($data['birthday']);
            }
            if(!empty($data['sex'])){
                if($data['sex'] == '男'){
                    $userModel->sex     = '1';
                }
                if($data['sex'] == '女'){
                    $userModel->sex     = '0';
                }
            }
            if(!empty($data['cardNumber']) && !empty($data['cardType'])){
                $userModel->card_type   = self::cardStr($data['cardType']);;
                $userModel->card_number = $data['cardNumber'];
            }

            $userModel->mail        = $data['mail'];
            $userModel->code        = User::randCodeGroup();
            $userModel->key         = $data['orderKey'];
            if(!empty($data['invite'])){
                $inviteData = User::findByCode($data['invite']);                // -邀请人信息
                if(!empty($inviteData)){
                    $userModel->invite_id       = $inviteData->id;
                    $userModel->invite_status   = User::INVITE_STATUS_YES;
                }
            }
            if($userModel->save()){
                // 查询用户是否有未付款的产品，如果有中断程序
                $isOpenOrder = static::userIsOpenOrder($data['wechatId'], $data['orderType'], $data['orderKey']);
                if($isOpenOrder) return ['code' => '-401', 'message' => '存在未完成订单！', 'data' => ['order_id' => $isOpenOrder->id]];
                $userId = $userModel->attributes['id'];
                // 受益人信息
                $benefitUserModel = new BenefitUser();
                $benefitUserModel->user_id               = $userId;
                $benefitUserModel->relation              = self::relation($data['relation']);
                $benefitUserModel->benefit_user_name     = $data['benefitUserName'];
                $benefitUserModel->benefit_user_num      = $data['benefitUserNum'];
                $benefitUserModel->benefit_card_type     = self::cardStr($data['benefitCardType']);
                if(!empty($data['benefitUserSex'])){
                    if($data['benefitUserSex'] == '男'){
                        $benefitUserModel->benefit_user_sex     = '1';
                    }
                    if($data['benefitUserSex'] == '女'){
                        $benefitUserModel->benefit_user_sex     = '0';
                    }
                }
                $benefitUserModel->benefit_user_phone    = $data['benefitUserPhone'];
                $benefitUserModel->benefit_user_mail     = $data['benefitUserMail'];
                $benefitUserModel->benefit_user_province = $data['benefitUserProvince'];
                $benefitUserModel->benefit_user_city     = $data['benefitUserCity'];
                $benefitUserModel->benefit_user_area     = $data['benefitUserArea'];
                $benefitUserModel->benefit_user_school   = $data['benefitUserSchool'];
                $benefitUserModel->key                   = $data['orderKey'];
                if($benefitUserModel->save()){
                    $benefitUserId = $benefitUserModel->attributes['id'];
                    $orderModel = new Order();
                    $orderModel->order_num  = $data['orderKey'].date('Ymd').substr(md5($userId),0,4).GnhString::randomNum(4);
                    $orderModel->user_id    = $userId;
                    $orderModel->wechat_id  = $data['wechatId'];
                    $orderModel->benefit_id = $benefitUserId;
                    $orderModel->amount     = $amount;
                    $orderModel->key        = $data['orderKey'];
                    $orderModel->type       = $data['orderType'];
                    if($orderModel->save()){
                        $transaction->commit();
                        return $orderModel->attributes['id'];
                    }
                }
            }
        } catch (\Exception $e) {
            $transaction->rollBack();
            return ['code' => -100 , 'message' => $e->getMessage()];
        }
    }

    public static function relation($relation = '')
    {
        if($relation == '本人'){return '1';}
        if($relation == '父母'){return '2';}
        if($relation == '同学'){return '3';}
        if($relation == '朋友'){return '4';}
        return '1';
    }

    public static function cardStr($cardType= '')
    {
        if($cardType == '身份证'){return '1';}
        return '1';
    }

    /**
     * 根据key查询产品内容
     * @param string $key
     * @return array
     */
    public static function goodsInfoService($key = 'kgb')
    {
        // 定义空数组（返回用）
        $data = [];

        // 这里的查询是拉出页面的标题和其他项，为空直接返回，这里为空页面都存在问题
        $goodsParams = GoodsParams::find()
            ->where(['key' => $key])
            ->andWhere(['is_valid' => BaseModels::MODEL_IS_VALID])
            ->select('label,type,content')
            ->orderBy('sort asc')
            ->asArray()
            ->all();
        if(empty($goodsParams)){
            return $data;
        }
        // 查询出首页产品顶部的保障项目
        $goodsRadio = GoodsRadio::find()
            ->where(['key' => $key])
            ->andWhere(['is_valid' => BaseModels::MODEL_IS_VALID])
            ->select('value,label as title')
            ->orderBy('sort desc')
            ->asArray()
            ->all();
        if(empty($goodsRadio)){
            $goodsRadio = [];
        }

        // 查询出首页产品中部的保障范围
        $goodsList = GoodsList::find()
            ->where(['key' => $key])
            ->andWhere(['is_valid' => BaseModels::MODEL_IS_VALID])
            ->select('label as value')
            ->orderBy('sort desc')
            ->asArray()
            ->all();
        if(empty($goodsList)){
            $goodsList = [];
        }

        // 查询出首页产品底部的保障套餐
        $goodsPack = GoodsPack::find()
            ->where(['key' => $key])
            ->andWhere(['is_valid' => BaseModels::MODEL_IS_VALID])
            ->select('label,content')
            ->orderBy('sort desc')
            ->asArray()
            ->all();
        if(empty($goodsPack)){
            $goodsPack = [];
        }
        // 处理数组，将其重新组合成前端使用的格式，有点麻烦，但是前端这样就能不需要再让后端重新开放。
        foreach ($goodsParams as $kParams => $vParams){
            $info = [];
            if(!empty($vParams['label'])){
                $info['label']      = $vParams['label'];
            }
            if(!empty($vParams['type'])){
                $info['type']       = $vParams['type'];
            }
            if(!empty($vParams['content'])){
                $info['content']    = $vParams['content'];
            }
            if(!empty($vParams['type']) && $vParams['type'] == GoodsParams::TYPE_RADIO){
                $info['content']    = $goodsRadio;
            }
            if(!empty($vParams['type']) && $vParams['type'] == GoodsParams::TYPE_LIST){
                $info['content']    = $goodsList;
            }
            array_push($data,$info);
        }
        // 多余项，只能单独处理了
        $item = [
            'detail' => $data,
            'pack'   => [
                'title' => BaseModels::GOODS_PACK,
                'item'  => $goodsPack,
            ],
        ];
        return $item;
    }

    /**
     * 根据用户id 查询出用户当前所拥有订单相关信息
     * @param $userId
     * @param $key
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function orderUserDataQuery($userId,$key)
    {
        if(empty($userId) || empty($key)){
            return [];
        }
        $data = Order::find()->from(Order::tableName().' as a ')
            ->leftJoin(BenefitUser::tableName().' as b ','a.benefit_id = b.id')
            ->where(['a.user_id' => $userId])
            ->andWhere(['a.key' => $key])
            ->select("a.id,a.order_num,a.order_status,a.amount,a.created_at,a.benefit_id,a.type,b.benefit_user_name")
            ->orderBy('a.id desc')
            ->asArray()
            ->all();
        return $data;
    }

    /**
     * 根据订单查出相关订单信息
     * @param $orderId
     * @param $key
     * @return array|null|\yii\db\ActiveRecord
     */
    public static function onlyOrderList($orderId,$key)
    {
        $orderData = Order::find()
            ->from(Order::tableName().' as a ')
            ->leftJoin(User::tableName().' as b ','a.user_id = b.id')
            ->leftJoin(BenefitUser::tableName().' as c ','a.benefit_id = c.id')
            ->where(['a.id' => $orderId])
            ->andWhere(['a.key' => $key])
            ->select("a.id,a.order_num,a.order_status,a.amount,a.key,a.type,a.created_at,a.benefit_id,a.user_id,a.benefit_id,b.user_name,b.phone,b.card_type,b.card_number,b.mail,c.benefit_user_name,c.benefit_card_type,c.benefit_user_num,c.benefit_user_phone,c.benefit_user_mail,c.benefit_user_school")
            ->limit(1)
            ->asArray()
            ->one();
        if(empty($orderData)){
            return [];
        }
        return $orderData;
    }

    /**
     * 根据订单查询出订单相对应的凭证信息
     * @param $orderId
     * @return array|null|\yii\db\ActiveRecord
     */
    public static function orderVoucher($orderId)
    {
        return BenefitImg::find()->where(['order_id' => $orderId])->limit(1)->one();
    }

}